package com.bestv.bsr.core.aspect;

import com.bestv.bsr.core.annotations.Sign;
import com.bestv.bsr.core.constants.ServiceCodeEnum;
import com.bestv.bsr.core.exceptions.ServiceException;
import com.bestv.bsr.core.properties.GlobalProperties;
import com.bestv.bsr.core.utils.ServletUtils;
import com.bestv.bsr.core.utils.SignUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 接口签名验证AOP
 *
 * @author taojiacheng
 */
@Aspect
@Component
@RequiredArgsConstructor
@Slf4j
public class SignAspect implements Ordered {

    private final GlobalProperties globalProperties;


    @Around("@annotation(sign)")
    public Object around(ProceedingJoinPoint joinPoint, Sign sign) throws Throwable {
        HttpServletRequest request = ServletUtils.getRequest();
        if (request == null) {
            throw new ServiceException(ServiceCodeEnum.PARAMETER_INVALID);
        }
        boolean check = SignUtils.check(request, globalProperties.getSignKey());
        if (!check) {
            throw new ServiceException(ServiceCodeEnum.SIGN_INVALID);
        }
        return joinPoint.proceed();
    }


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
